package com.hanlin.day07;

import com.hanlin.day06.MaxBTree;
import com.hanlin.type.TreeNode;

/**
 * 描述：https://leetcode.cn/problems/balanced-binary-tree/
 * 平衡二叉树
 *
 * @author:hl.yuan
 * @date:2022-08-07
 */
public class Solution110 {


    /**
     * 判断是否是平衡二叉树
     *
     * @param root
     * @return
     */
    public boolean isBalanced(TreeNode root) {
        height(root);
        return res;
    }

    public static class info {
        public boolean isBalanced;
        public int height;

        public info(){}
        public info(boolean isBalanced,int height){
            this.isBalanced = isBalanced;
            this.height = height;
        }

    }

    public static info process(TreeNode root) {
        if (root == null) {
            return new info(true, 0);
        }
        // 得到左树的info对象
        info processLeft = process(root.left);
        // 得到右树的info对象
        info processRight = process(root.right);
        int height = Math.max(processLeft.height, processRight.height) + 1;
        Boolean isBalanced = processLeft.isBalanced && processRight.isBalanced && Math.abs(processLeft.height- processRight.height)<2;
        return new info(isBalanced,height);
    }
    /***************************************************************************************/

    public static Boolean res = true;

    public static int height(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int heightLeft = height(root.left)+1;
        int heightRight = height(root.right)+1;

        if (Math.abs(heightLeft - heightRight) > 1) {
            res = false;
            return 0;
        }
        return Math.max(heightLeft,heightRight);
    }

    public static void main(String[] args) {
        TreeNode node = new TreeNode(1);
        node.left = new TreeNode(2);
        node.right = new TreeNode(2);
        node.left.left = new TreeNode(3);
        node.left.right = new TreeNode(3);
        node.left.left.left = new TreeNode(4);
        node.left.left.right = new TreeNode(4);

//        height(node);

        int maxDepth = MaxBTree.maxDepth(node);
        System.out.println(maxDepth);
    }

}


